const flattenToArray = (data) => {
  let result = [];
  for (const item of data) {
    if (item.children) {
      const itemBack = { ...item };
      Reflect.deleteProperty(itemBack, "children");
      result.push(itemBack);
      result = result.concat(flattenToArray(item.children));
    } else {
      result.push(item);
    }
  }
  return result;
};

const flattenToObject = (data, resType = "Array", resKey) => {
  let result = {};

  for (const item of data) {
    const itemBack = { ...item };
    Reflect.deleteProperty(itemBack, "children");
    result[itemBack[`${resKey}`]] = itemBack;

    if (item.children) {
      const res = flattenToObject(item.children, resType, resKey);
      result = { ...result, ...res };
    }
  }
  return result;
};

/**
 *
 * @param {Array} data
 * @param {String} resType 结果类型 对象/数组
 * @param {String} resKey 对象结果类型时指定key
 * @returns
 */
const handleFlatten = (data, resType = "Array", resKey) => {
  if (resType === "Object" && !!resKey) {
    return flattenToObject(data, resType, resKey);
  } else {
    return flattenToArray(data);
  }
};

export default handleFlatten;
